package com.manger.format;

import com.manger.common.office.sax.ExcelFactory;
import com.manger.model.GoodPay;
import com.manger.model.JR;
import com.manger.model.Project;
import com.manger.utils.CopyFiles;
import com.manger.utils.DetNameEnum;
import com.manger.utils.LoanFileEnum;
import com.manger.utils.SystemConstant;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName JiRongCaseFilesFormat
 * @Description TODO
 * @Author @LiuHongJun
 * @Date 2025/9/5 20:31
 * @Version 1.0
 */
public class JiRongCaseFilesFormat implements CaseFilesFormat{

    private static Map<String, LoanFileEnum> filesMapping = new HashMap<>();

    {
        filesMapping.put("民事起诉状",LoanFileEnum.INDICTMENT);
        filesMapping.put("授权委托书",LoanFileEnum.ENTRUSTMENT_INFORMATION);
        filesMapping.put("送达地址确认书",LoanFileEnum.CONFIRMATION_DELIVERY_ADDRESS);
        filesMapping.put("申请方营业执照-法人身份证明",LoanFileEnum.PART_IDENTITY_CERTIFICATE);
    }

    @Override
    public void format(String extractDir, String targetDir, Project project) throws Exception {
        String excelFilePath = extractDir + "/" + SystemConstant.ENTRUSTED_INFO;
        File excelFile = new File(excelFilePath);
        System.out.println(excelFile.getCanonicalPath());
        if(!excelFile.exists()){
            return;
        }
        Map<String , List<?>> map = ExcelFactory.getExcelFactory().getParseExecutor().parse(excelFile, JR.class).get();
        if(map == null || map.isEmpty()){
            return;
        }
        List<JR> errorList = new ArrayList<>();
        List<JR> jrList = (List<JR>)  map.get(map.keySet().iterator().next());
        Map<String,Map<String,String>> jrNameMap = new HashMap<>();
        Map<String,Integer> idCardMap = new HashMap<>();
        for(JR jr : jrList){
            if(idCardMap.containsKey(jr.getIdCard())){
                idCardMap.put(jr.getIdCard(),idCardMap.get(jr.getIdCard())+1);
            }else {
                idCardMap.put(jr.getIdCard(),1);
            }
        }
        for(JR jr : jrList){
            if(idCardMap.containsKey(jr.getIdCard()) && idCardMap.get(jr.getIdCard()) > 1){
                continue;
            }
            String tempJrDir = extractDir + "/" + jr.getSubjectLitigation() + "/" + "原始材料" + "/" + jr.getCaseCode();
            String tempTargetDir = targetDir + "/" + project.getDebtName()  + "/" + jr.getSubjectLitigation() + "/"
                    + SystemConstant.CASE_FILE_DIR_NAME + "/" + jr.getUserName() + "-" + jr.getIdCard();
            File file = new File(tempJrDir);
            if(!file.exists()){
                continue;
            }
            if(!jrNameMap.containsKey(jr.getSubjectLitigation())){
                File tempFileDir = new File(extractDir + "/" + jr.getSubjectLitigation() + "/" + "所函" );
                if(!tempFileDir.exists()){
                    jrNameMap.put(jr.getSubjectLitigation(),new HashMap<>());
                }else {
                    Map<String,String> tempMap = new HashMap<>();
                    File[] tempFiles = tempFileDir.listFiles();
                    for(File tempFile: tempFiles){
                        String key = tempFile.getName().substring(0, tempFile.getName().indexOf("-"));
                        tempMap.put(key,tempFile.getCanonicalPath());
                    }
                    jrNameMap.put(jr.getSubjectLitigation(),tempMap);
                }
            }
            try{
                File targetFileDir = new File(tempTargetDir);
                if(!targetFileDir.exists()){
                    targetFileDir.mkdirs();
                }
                File[] tempFiles = file.listFiles();
                CopyFiles.createDirs(tempTargetDir);
                for(File tempFile: tempFiles){
                    String targetRealPath = tempTargetDir + "/" + CopyFiles.getLoanFileEnum(tempFile.getName(),filesMapping).getName();
                    CopyFiles.copyFileToDir(tempFile.getAbsolutePath(),targetRealPath );
                }
                CopyFiles.copyBaseFiles(tempTargetDir, project);
                //拷贝所涵
                String shPath = jrNameMap.get(jr.getSubjectLitigation()).get(jr.getCaseCode());
                if(StringUtils.isEmpty(shPath)){
                    continue;
                }
                CopyFiles.copyFileToDir(shPath,tempTargetDir + "/" + LoanFileEnum.ENTRUSTMENT_INFORMATION.getName());
                System.out.println("整理原始数据成功：【" + jr.getUserName() + "-" + jr.getIdCard() + "】");
            }catch (Exception e){
                errorList.add(jr);
                e.printStackTrace();
                System.out.println("整理原始数据失败：【" + jr.getUserName() + "-" + jr.getIdCard() + "】");
            }
        }
        if(!errorList.isEmpty()){
            String errorFilePath = targetDir + "/" + project.getDebtName() + "/" + SystemConstant.ERROR_EXCEL_PRE + System.currentTimeMillis() + ".xlsx";
            ExcelFactory.getExcelFactory().getExportExecutor().sheet("整理错误")
                    .data(errorList).head(GoodPay.class).write(new FileOutputStream(errorFilePath));
            System.out.println("导出整理错误数据【"+errorFilePath+"】");
        }
    }

    public static void main(String[] args) throws Exception{
        JiRongCaseFilesFormat jiRongCaseFilesFormat = new JiRongCaseFilesFormat();
        String targetDir = SystemConstant.getFormatDir() + "/" + "target" + "/" + "123456";
        String extractDir = "D:\\workSpace\\AutomaticCase\\AutomaticFiling/../format\\1756990856368\\极融";
        Project project = new Project();
        project.setDebtName(DetNameEnum.JR.getDesc());
        jiRongCaseFilesFormat.format(extractDir,targetDir,project);
    }
}
